package com.yhy.common.excel.utils;

import cn.hutool.core.io.IoUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.http.HttpHeaders;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Excel工具类 - EasyExcel
 */
@Slf4j
@UtilityClass
public class EasyExcelUtil {

    private final ThreadLocal<StopWatch> invokeTime = new ThreadLocal<>();

    private static final String XLSX_SUFFIX = ".xlsx";

    @SneakyThrows(value = UnsupportedEncodingException.class)
    public void exportExcel(HttpServletResponse response, List<?> dataList, String fileName, String sheetName) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String name = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + name + XLSX_SUFFIX);
        response.setHeader(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            EasyExcel.write(outputStream, dataList.get(0).getClass()).sheet(sheetName).doWrite(dataList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭输出Servlet流
        IoUtil.close(outputStream);
        stopWatch.stop();
        log.info("导出excel耗时: {}毫秒", stopWatch.getTime());
    }

    public String generateExcel(List<?> dataList, String fileName, String sheetName) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        invokeTime.set(stopWatch);
        String path = "./" + fileName + XLSX_SUFFIX;
        EasyExcel.write(path, dataList.get(0).getClass()).sheet(sheetName).doWrite(dataList);
        stopWatch.stop();
        log.info("生成excel耗时: {}毫秒", stopWatch.getTime());
        return path;
    }

    @SneakyThrows(value = IOException.class)
    public static void importExcel(MultipartFile file, Class<?> clazz, AnalysisEventListener<?> listener) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        EasyExcel.read(file.getInputStream(), clazz, listener).sheet().doRead();
        stopWatch.stop();
        log.info("解析excel耗时: {}毫秒", stopWatch.getTime());
    }

}
